package net.tribal.comic.controllers

import net.tribal.comic.entities.User

class UserController {
	def userService
	
	/**
	 * default action
	 */
    def index = { redirect(action: "list", params: params) }

	/**
	 * the delete, save and update actions only accept POST requests
	 */
    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

    /**
     * 
     */
    def list = {
        params.max = Math.min(params.max ? params.max.toInteger() : 10,  100)
        [userInstanceList: User.list(params), userInstanceTotal: User.count()]
    }


	/**
     * 
     */
    def create = {
        def userInstance = new User()
        userInstance.properties = params
        return [userInstance: userInstance]
    }


	/**
     * Save User instance
     */
    def save = {
		def instance = new User(params)
		instance.repeatPassword = params.repeatPassword
    	instance = userService.add( new User(params), request.getFile('file'), params.password, params.repeatPassword )
		if(!instance.hasErrors()){
			flash.message = "user.created"
            flash.args = [instance.id]
            flash.defaultMessage = "User ${instance.id} created"
            redirect(action: "show", id: instance.id)
    	}
		else { render(view: "create", model: [userInstance: instance]) }
    }

	
	/**
     * 
     */
    def show = {
        def userInstance = User.get(params.id)
        if (!userInstance) {
            flash.message = "user.not.found"
            flash.args = [params.id]
            flash.defaultMessage = "User not found with id ${params.id}"
            redirect(action: "list")
        }
        else {
            return [userInstance: userInstance]
        }
    }


	/**
     * 
     */
    def editProfile = {
		def userInstance = User.get(params.id)
        if (!userInstance) {
            flash.message = "user.not.found"
            flash.args = [params.id]
            flash.defaultMessage = "User not found with id ${params.id}"
            redirect(action: "list")
        }
        else {
        	render ( view:"editProfile", model:[userInstance: userInstance] )
        }
    }


	/**
     * 
     */
	def editPassword = {
		def userInstance = User.get(params.id)
        if (!userInstance) {
            flash.message = "user.not.found"
            flash.args = [params.id]
            flash.defaultMessage = "User not found with id ${params.id}"
            redirect(action: "list")
        }
        else {
        	render ( view:"editPassword", model:[userInstance: userInstance] )
        }
    }


	/**
     * 
     */
	def editFile = {
		def userInstance = User.get(params.id)
        if (!userInstance) {
            flash.message = "user.not.found"
            flash.args = [params.id]
            flash.defaultMessage = "User not found with id ${params.id}"
            redirect(action: "list")
        }
        else {
        	render ( view:"editFile", model:[userInstance: userInstance] )
        }
    }


	/**
     * 
     */
	def updateProfile = {
		def userInstance = User.get (params.id)
		if ( !userInstance ) {
			flash.message = "user.not.found"
            flash.args = [params.id]
            flash.defaultMessage = "User not found with id ${params.id}"
            redirect(action: "list")
            return
		}
		
		userInstance.properties = params
		userInstance = userService.changeProfile ( userInstance )
		
		if ( userInstance.hasErrors() ) {
			render(view: "editProfile", model: [userInstance: userInstance])
    	}else{
    		flash.message = "user.updated"
            flash.args = [params.id]
            flash.defaultMessage = "User ${params.id} updated"
            redirect(action: "show", id: userInstance.id)
    	}
	}


	/**
     * 
     */
	def updatePassword = {
		def userInstance = User.get (params.id)
		if ( !userInstance ) {
			flash.message = "user.not.found"
            flash.args = [params.id]
            flash.defaultMessage = "User not found with id ${params.id}"
            redirect(action: "list")
            return
		}

		userInstance = userService.changePassword ( userInstance, params.password, params.repeatPassword )
		
		if ( userInstance.hasErrors() ) {
			render(view: "editPassword", model: [userInstance: userInstance])
    	}else{
    		flash.message = "user.updated"
            flash.args = [params.id]
            flash.defaultMessage = "User ${params.id} updated"
            redirect(action: "show", id: userInstance.id)
    	}
	}


	/**
     * 
     */
	def updateFile = {
		def userInstance = User.get (params.id)
		if ( !userInstance ) {
			flash.message = "user.not.found"
            flash.args = [params.id]
            flash.defaultMessage = "User not found with id ${params.id}"
            redirect(action: "list")
            return
		}

		userInstance = userService.changeFile ( userInstance, request.getFile('file') )

		if ( userInstance.hasErrors() ) {
			render(view: "editPassword", model: [userInstance: userInstance])
    	}else{
    		flash.message = "user.updated"
            flash.args = [params.id]
            flash.defaultMessage = "User ${params.id} updated"
            redirect(action: "show", id: userInstance.id)
    	}
	}
	

	/**
     * 
     */
    def delete = {
		def instance = userService.delete( User.get(params.id) )
		if ( !instance ) {
			flash.message = "user.not.found"
			flash.args = [params.id]
			flash.defaultMessage = "User not found with id ${params.id}"
			redirect(action: "list")
			return
		}
		
		
		if (!instance.hasErrors()) {
			session.invalidate()
			flash.message = "user.deleted"
            flash.args = [params.id]
            flash.defaultMessage = "User ${params.id} deleted"
            redirect(action: "list")
            
		} else {
			flash.message = "user.not.deleted"
            flash.args = [params.id]
            flash.defaultMessage = "User ${params.id} could not be deleted"
            redirect(action: "show", id: instance.id)
		}
    }
    

	/**
     * Change swap lightbox and list views 
     */
	def changeView = {
		session['userViewMode'] = (session['userViewMode'] == 'list') ? "flow" : "list"
		redirect(action: "list", params: params)
	}


	/**
	 * 
	 */
    def enable = {
		def instance = User.get(params.id)
    	instance.disabled = false
		
    	def result = userService.update( null, instance )
    	if(result != null) {
        	if(result.hasErrors()){
        		render(view: "edit", model: [userInstance: result])
        	}else{
        		flash.message = "user.updated"
                flash.args = [params.id]
                flash.defaultMessage = "User ${params.id} updated"
                redirect(action: "show", id: result.id)
        	}
        }else{
            flash.message = "user.not.found"
            flash.args = [params.id]
            flash.defaultMessage = "User not found with id ${params.id}"
            redirect(action: "edit", id: params.id)
        }
    }


	/**
	 * 
	 */
    def disable = {
		def instance = User.get(params.id)
		instance.disabled = true
		
    	def result = userService.update( null, instance )
    	if(result != null) {
        	if(result.hasErrors()){
        		render(view: "edit", model: [userInstance: result])
        	}else{
        		flash.message = "user.updated"
                flash.args = [params.id]
                flash.defaultMessage = "User ${params.id} updated"
                redirect(action: "show", id: result.id)
        	}
        }else{
            flash.message = "user.not.found"
            flash.args = [params.id]
            flash.defaultMessage = "User not found with id ${params.id}"
            redirect(action: "edit", id: params.id)
        }
    }


	/**
	 * Busquem totes les aportacions del usuari 
	 */
    def myContributions = {
		def result = ""
		def x = Comic.findAllByCreatedBy(User.get(params.id))
		if(x) {
			result = "<ul>Comics"
			x.each() {
				result += "<li>" + it.name + "</li>"
				x = Page.findAllWhere("createdBy":User.get(params.id), "comic":it)
				x.each() {
					result += "<li>" + it.name + "</li>"
					x = AlterPage.findAllWhere("createdBy":User.get(params.id), "homePage":it)
				}
			}
			result += "</ul>"
		}
		render(result)
	}
	

	/**
	 * 
	 */
	def filterListAjax = {
	    params.max = Math.min(params.max ? params.max.toInteger() : 10,  100)
		def results = (User.createCriteria()).list {
			if(params.value) { ilike("name", "%"+params.value+"%") }
		}
		render(template: "listContent", model: [userInstanceList: results, userInstanceTotal: results.size()])
	}
}